package com.come4loves.core.comunicate.codec;

import io.netty.buffer.ByteBuf;

import com.come4loves.core.comunicate.protocol.DataPacket;
import com.come4loves.core.utils.SecurityUtils;

public class ServerDecoderCrypt extends BaseDecoder {
	

	@Override
	protected Object decode(ByteBuf in, int messageLen) throws Exception {
		
		byte module = in.readByte();
		byte cmd = in.readByte();
		int hashCode = in.readInt();
		byte crypt = in.readByte();
		int args = in.readInt();
		byte[] valueData = new byte[messageLen - 11];
		in.readBytes(valueData);
		if (crypt == 1) {
			valueData = SecurityUtils.decrypt(valueData, CryptKeyManager.getKey());
		}
		int cacleValue = cacleHashCode(valueData);
		if (cacleValue != hashCode) {
			LOGGER.warn(String
					.format("hashcode error: [module: %d, cmd: %d, hashCode: %d, calcHashCode: %d]",
							module, cmd, hashCode, cacleValue));
			return null;
		}
		DataPacket dataPackage = new DataPacket(module, cmd, args, valueData);
		return dataPackage;
	}
}
